// pages/msgdet/index.js
import { Sysmsg } from '../../model/sysmsg-model.js';
var sysmsg = new Sysmsg();
import {
  Company
} from '../../model/company-model.js';

var company = new Company();
Page({
  data: {
    id: -1,
    msgType: 1,           // 1-求职者，2-企业
    job_seeker_id: -1,
    enterprise_id: -1,
    sender_id: -1,
    history: [],           // 消息历史记录
    inputContent: '',      // 输入框内容
    scrollTop: 0,          // 滚动位置
    jobSeekerName: '',     // 求职者名称
    jobSeekerAvatar: '/images/default-avatar.png', // 求职者头像
    enterpriseName: '',    // 企业名称
    enterpriseAvatar: '/images/default-enterprise.png', // 企业头像
    pollingTimer: null,    // 轮询定时器ID
    isLoading: false,      // 是否正在加载消息
    scrollIntoView: '',
    showSheet: false,
    pollInterval: 5000     // 轮询间隔
  },

  onLoad(options) {
    // 初始化参数
    this.setData({
      job_seeker_id: options.job_seeker_id || -1,
      enterprise_id: options.enterprise_id || -1,
      sender_id: options.sender_id || -1,
      enterpriseName: options.enterprise_name ||''
    });

    // 根据 ctoken 判断当前端
    let ctoken = wx.getStorageSync('ctoken');
    if (ctoken) {
      this.setData({
        msgType: 2,        // 企业端
        sender_id: this.data.enterprise_id
      });
    } else {
      this.setData({
        msgType: 1,        // 求职者端
        sender_id: this.data.job_seeker_id
      });
    }

    // 获取历史消息，页面初次加载滚动到底部
    this.getHistorySysmsg(true);
  },

  onShow() {
    this.startPolling();
  },

  onHide() {
    this.clearPolling();
  },

  onUnload() {
    this.clearPolling();
  },

  startPolling() {
    this.clearPolling();
    const timer = setInterval(() => {
      if (!this.data.isLoading) {
        // 轮询时不滚动
        this.getHistorySysmsg(false);
      }
    }, this.data.pollInterval);
    this.setData({ pollingTimer: timer });
  },

  clearPolling() {
    if (this.data.pollingTimer) {
      clearInterval(this.data.pollingTimer);
      this.setData({ pollingTimer: null });
    }
  },

  // 获取历史消息
  getHistorySysmsg(scrollToBottomAfterLoad = false) {
    let that = this;
    that.setData({ isLoading: true });
    let params = {
      sender_type: this.data.msgType,
      enterprise_id: this.data.enterprise_id,
      job_seeker_id: this.data.job_seeker_id,
      sender_id: this.data.sender_id
    };
    let ctoken = wx.getStorageSync('ctoken');
    if (ctoken) params.ctoken = ctoken;

    sysmsg.getHistorySysmsg((data) => {
      that.setData({ isLoading: false });

      if (data.code === 1 && data.data && data.data.history) {
        const history = data.data.history;
        const jobSeekerInfo = history.find(item => item.sender_type === 1);
        const enterpriseInfo = history.find(item => item.sender_type === 2);

        const updateData = {
          history: history,
          id: data.data.id
        };

        console.log("jobSeekerInfo",jobSeekerInfo,"enterpriseInfo",enterpriseInfo)
        if (jobSeekerInfo) {
          updateData.jobSeekerName = jobSeekerInfo.nickname || '求职者';
          updateData.jobSeekerAvatar = jobSeekerInfo.avatarUrl || this.data.jobSeekerAvatar;
        }

        if (enterpriseInfo) {
          updateData.enterpriseName = enterpriseInfo.nickname || '企业';
          updateData.enterpriseAvatar = enterpriseInfo.avatarUrl || this.data.enterpriseAvatar;
        }else{
          updateData.enterpriseName = that.data.enterpriseName || '企业';
        }

        that.setData(updateData, () => {
          // 设置标题为对方姓名
          let title = this.data.msgType === 1 ? updateData.enterpriseName : updateData.jobSeekerName;
          console.log(title)
          wx.setNavigationBarTitle({ title });

          // 标记消息为已读
          this.markAsRead(data.data.id);

          // 页面初始化或发送消息后滚动到底部
          if (scrollToBottomAfterLoad) {
            this.scrollToBottom()
          }
        });
      }
    }, params);
  },

  // 标记消息为已读
  markAsRead(conversationId) {
    let params = { id: conversationId };
    let ctoken = wx.getStorageSync('ctoken');
    if (ctoken) params.ctoken = ctoken;
    sysmsg.toRedById(() => {}, params);
  },

  // 时间格式化
  formatTime(timestamp) {
    const date = new Date(parseInt(timestamp) * 1000);
    return `${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}`;
  },

  // 判断是否为图片
  isImage(url) {
    if (!url) return false;
    const imageExtensions = ['jpg','jpeg','png','gif','bmp','webp'];
    const ext = url.split('.').pop().toLowerCase();
    return imageExtensions.includes(ext);
  },

  // 文件大小格式化
  formatFileSize(size) {
    if (size === 0) return '0 B';
    const k = 1024;
    const sizes = ['B','KB','MB','GB'];
    const i = Math.floor(Math.log(size)/Math.log(k));
    return parseFloat((size/Math.pow(k,i)).toFixed(2)) + ' ' + sizes[i];
  },

  // 输入框
  onInput(e) {
    this.setData({ inputContent: e.detail.value });
  },

  // 发送消息
  sendMessage() {
    const content = this.data.inputContent.trim();
    if (!content) return;

    let params = {
      sender_type: this.data.msgType,
      receiver_type: this.data.msgType === 1 ? 2 : 1,
      enterprise_id: this.data.enterprise_id,
      job_seeker_id: this.data.job_seeker_id,
      file_url:'',
      content: content,
      message_type: 1
    };
    let ctoken = wx.getStorageSync('ctoken');
    if (ctoken) params.ctoken = ctoken;

    wx.showLoading({ title: '发送中...', mask: true });

    sysmsg.sendSysmsg((res) => {
      wx.hideLoading();
      if (res.code === 1) {
        this.setData({ inputContent: '' });
        // 发送消息后滚动到底部
        this.getHistorySysmsg(true);
      } else {
        wx.showToast({ title: '发送失败，请重试', icon: 'none' });
      }
    }, params);
  },

  // 滚动到底部
  scrollToBottom() {
    this.setData({ scrollTop: 999999 });
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original','compressed'],
      sourceType: ['album','camera'],
      success: (res) => {
        this.uploadFile(res.tempFilePaths[0], 2);
      }
    });
  },
  showActionSheet() {
    this.setData({ showSheet: true });
  },

  hideActionSheet() {
    this.setData({ showSheet: false });
  },
  noop() {
    // 阻止事件冒泡
  },

  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const tempFile = res.tempFiles[0];
        this.uploadFile(tempFile.path,3,tempFile.name,tempFile.size);
      }
    });
  },
  uploadFile(filePath, type, fileName = '', fileSize = 0) {
    let ctoken = wx.getStorageSync('ctoken');
    let params = { path: filePath };
    if (ctoken) params.ctoken = ctoken;
  
    // 显示上传提示
    wx.showLoading({ title: '正在上传...', mask: true });
  
    company.uploadimg(
      (data) => {
        console.log(data);
        wx.hideLoading(); // 上传结束，关闭 loading
        if (data.code == 1) {
          let sendparams = {
            sender_type: this.data.msgType,
            receiver_type: this.data.msgType === 1 ? 2 : 1,
            enterprise_id: this.data.enterprise_id,
            job_seeker_id: this.data.job_seeker_id,
            content: this.data.inputContent.trim(),
            message_type: type,
            file_url: data.data.url,
          };
  
          // 发送消息
          sysmsg.sendSysmsg((res) => {
            if (res.code === 1) {
              this.setData({ inputContent: '' });
              this.getHistorySysmsg(true); // 滚动到底部
            } else {
              wx.hideLoading();
              wx.showToast({ title: '消息发送失败', icon: 'none' });
            }
          }, sendparams);
  
        } else {
          setTimeout(() => {
            wx.showToast({
              title: (data.msg || '上传失败'), // 限制长度
              icon: 'none', // 显式指定，避免默认success图标导致的问题
              duration: 2000,
              mask: false // 通常toast不需要mask
            });
          }, 100);
        }
      },
      params
    )
  },
  
  previewFile(e) {
    const fileUrl = e.currentTarget.dataset.url; // 获取文件地址
    if (!fileUrl) {
      wx.showToast({
        title: '文件不存在',
        icon: 'none'
      });
      return;
    }

    // 调用小程序API打开文件
    wx.downloadFile({
      url: fileUrl, // 网络文件地址
      success: res => {
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            success: () => {
              console.log('打开文件成功');
            },
            fail: err => {
              console.error('打开文件失败', err);
              wx.showToast({
                title: '无法打开文件',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('下载文件失败', err);
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        });
      }
    });
  },
  // 点击图片预览
  previewImage(e) {
    const currentUrl = e.currentTarget.dataset.url;
    const urls = [currentUrl]

    wx.previewImage({ current: currentUrl, urls: urls });
  },

  onBack() {
    wx.navigateBack({ delta: 1 });
  }
});
